require "Common/define"
require "Logic/Config"
require "Common/functions"
require "Net/drawHandler"

UIDraw = {};
HelperFunc.SetUIEnv(UIDraw)
local this = UIDraw;

this._spineOutInSpeed = 0.09; -- 越大越快,最大1,最小0
this.startDragPosX = nil;
this.btnLast = nil;
this.btnNext = nil;
this.btnLook = nil;
this.btn_DrawOne = nil;
this.topRedDos = {};
this.btn_DrawTen = nil;
this.btn_Shop = nil;
this.txt_DrawOneCost = nil;
this.txt_DrawTenCost = nil;
this.content = nil;
this.itemPrice = 200;
this.tab_top = { "1", "2","6" }
this.showTab = {};
--this.tab_poolIds = { "1", "2", "3", "4", "5", "6", "7", "8" }
this.tab_topItem = {}
this.tab_cards = {};
this.hasHeroIds = {};
this.curShowIndex = 1;
this.curPoolId = nil;
this.curpage = 1;
this.curisHerotype=false;
this.btnDownState = false;
this.isScroll = false;
this.title = nil;
this.cash = nil;
this.coin = nil;
this.topRedPool = {};
this.topRedCount = 0;
this.oneIcon = nil;
this.tenIcon = nil;
this.buyTime = nil;
this.resTab = {}
this.img_Icon = nil;
this.txt_name = nil;
this.txt_level = nil;
this.btn_head = nil;
this.exp = nil;
this.btnWish = nil;
this.cards = {};
UIDraw.OpenState = {}
this.aniRightOut = nil;
this.aniRightIn = nil;
this.aniLeftOut = nil;
this.aniLeftIn = nil;
this.spineSprine = {};
this.drawWrappers = {};
this.state=nil;
--this.choosehero=nil;    

this.effectController=nil;
this.showSourceController=nil;
this.sourceUIobj=nil;
this.curDrawInfo = nil;
this.chooseText=nil;
this.seleText=nil;
this.curDrawInfo = nil;
this.isGuiding = false;
this.btnChangeOccupation=nil;
this.btnChangeOccupationtitle=nil;
this.btnSeletOccupation=nil;
this.btnSeletOccupationtitle=nil;
this.HeroTypeIcon1=nil;
this.HeroTypeIcon2=nil;
this.HeroTypetitle1=nil;
this.HeroTypetitle2=nil;
this.wishBnt = nil
this.wishHeroList = nil

this.btnOpenTips={}
this.btnCloseTips={}
this.btnDrawBox={}
this.btnCloseReward={}
this.barDraw={}
this.ctTips={}
this.ctRewards={}
this.boxRewardsList={}
this.txtDesc={}
this.isdirecting=false;--是否定向
this.dirTips=true;--定向标记
this.selecthero=nil;
this.dirnum=nil;
this.occupationnum=nil;
this.occuTipsnum=nil;
this.isoccupation=false;--是否选择职业
this.heroshowTab={};
this.redDotsten=nil;
this.occhero1=nil;
this.occhero2=nil;
this.SetcurpooId=nil;
this.ctrlBanClick=nil
this.wishList = nil
this.appointHeroList = nil
local SHOP_ID = 11000
local lastDrawNum=0
this.ctBox={}
this.Tweeners={}
this.wishCtrl = nil
this.allCount = nil
this.noLimitCtrl = nil
this.selectHeroCtrl = nil
this.noLimitheroCom = nil
this.noLimitHero_1 = nil
this.noLimitHero_2 = nil
this.notLimitHeroList = nil
this.wishHerosList = nil
this.typeHeros = {}
this.typeCtrl = nil
this.btn_Sure = nil
this.comHeroList = nil
this.wishIds = {0,0}
this.hasWishIds = {}
this.modelList = {}
this.btnToggle = nil
this.globalWish = nil
this.wishIndex = nil
this.wishTips = nil
this.wishTipsTitle = nil
this.onlyTenCtrl = nil
this.lastBuyTime = nil;

--- 免费召唤倒计时计时器
local mFreeSummonTimerId = nil
--- 红魔石召唤状态
local mDiamondSummonState = nil

-- 召唤状态
local SUMMON_STATE = {
    Normal = 0,  -- 常规消耗
    Time   = 1,  -- 倒计时
    Free   = 2   -- 免费
}

function UIDraw.Init(n)
    this.dirstage= G.dataTable["t_functionswitch"][tostring(512)]["f_UnlockStage"];
    this.HeroType=G.dataTable["t_drawpoolherotype"];
    this.SetcurpooId=n;
    
    local name, packageName = getUIName(PanelResNames.UIDraw);
    panelMgr:Push(name, packageName, this.onCreate, Config.useLocalUI);

end

--定义控件
function UIDraw.onCreate(obj)
    drawHandler.SendAppointDrawInfo();
    drawHandler.SendVocationDrawInfo();
    --btn_Prev = transform:Find("btnpre");
    --btn_Next = transform:Find("btnnext");
    comHeroList = obj:GetChild("heroList")
    notLimitHeroList = comHeroList:GetChild("list")
    this.typeCtrl = comHeroList:GetController("ctrlHeroType")
    btn_Sure = comHeroList:GetChild("btnBack")
    this.noLimitheroCom = obj:GetChild("Com_WishSelect07")
    this.noLimitHero_1 = this.noLimitheroCom:GetChild("Btn_Wish01")
    this.noLimitHero_2 = this.noLimitheroCom:GetChild("Btn_Wish02")
    this.noLimitCtrl = obj:GetController("ctrlSelectGroup")
    this.selectHeroCtrl = obj:GetController("ShowList")
    this.onlyTenCtrl = obj:GetController("drawtype")
    wishTips = obj:GetChild("tips1")
    this.tips = obj:GetChild("tips")
    wishTipsTitle = obj:GetChild("title4")
    btnToggle = obj:GetChild("btnQuite")
    btnLast = obj:GetChild("Btn_Before");
    btnNext = obj:GetChild("Btn_Next");
    this.titleName = obj:GetChild("Text_CardName");
    curpage = 1;
    btnLook = obj:GetChild("btnLook");
    btn_DrawOne = obj:GetChild("btndraw1");
    btn_DrawTen = obj:GetChild("btndraw10");
    redDotsten=btn_DrawTen:GetChild("UIRedDots");
    btn_Shop = obj:GetChild("btnShop");
    btn_SelectHero=obj:GetChild("n79");
    state=obj:GetController("state");
    --choosehero=obj:GetController("choosehero");   
    --ChooseHeroPanel=obj:GetChild("ChooseHero");
    ChooseBtn=obj:GetChild("ChooseBtn");
    chooseText=ChooseBtn:GetChild("BtnName");
    seleText=obj:GetChild("n79"):GetChild("n81");
    Heroname=obj:GetChild("n86"):GetChild("HeroName");
    btnSource=obj:GetChild("btnSource");
    btnresource=obj:GetChild("resource");
    resource=obj:GetChild("resource"):GetChild("title");
    iconresource=obj:GetChild("resource"):GetChild("icon");
    effectController = btnSource:GetController("effect");
    showSourceController = obj:GetController("showSource")
    sourceUIobj = obj:GetChild("n104");
    -- Herolist=ChooseHeroPanel:GetChild("n95");
    -- choose=ChooseHeroPanel:GetChild("choose");
    -- btn_ture=ChooseHeroPanel:GetChild("n103");
    btnChangeOccupation=obj:GetChild("btnChangeOccupation");
    btnChangeOccupationtitle=btnChangeOccupation:GetChild("title");
    btnSeletOccupation=obj:GetChild("btnSeletOccupation");
    btnSeletOccupationtitle=btnSeletOccupation:GetChild("n81");
    txt_DrawOneCost = btn_DrawOne:GetChild("num1");
    txt_DrawTenCost = btn_DrawTen:GetChild("num1");
    HeroTypeIcon1=obj:GetChild("occupationInfo"):GetChild("occupation1");
    HeroTypeIcon2=obj:GetChild("occupationInfo"):GetChild("occupation2");
    HeroTypetitle1=obj:GetChild("occupationInfo"):GetChild("text1");
    HeroTypetitle2=obj:GetChild("occupationInfo"):GetChild("text2");
    --content = obj:GetChild("content");
    title = getUI(PanelResNames.UIHeadMenu);
    cash = title:GetChild("CashLb");
    coin = title:GetChild("CoinLb");
    oneIcon = btn_DrawOne:GetChild("cost");
    tenIcon = btn_DrawTen:GetChild("cost");
    btnWish = obj:GetChild("btnWish");
    btnWish.title = getLanguage("WishFountain_Btn");
    this.wishEffect = btnWish:GetController("effect");
    btn_head = title:GetChild("Head");
    img_Icon = btn_head:GetChild("icon");
    txt_name = title:GetChild("Name");
    txt_level = title:GetChild("Level");
    exp = title:GetChild("exp")
    --抽卡进度相关

    btnDrawBox=obj:GetChild("Btn_DrawBox")
    barDraw=obj:GetChild("Bar_DrawProgress")
    boxRewardsList=obj:GetChild("List_BoxRewards")
    txtDesc=obj:GetChild("Text_DrawBoxDesc")
    txtDrawBox=obj:GetChild("Text_DrawBox")
    txtBaoDi=obj:GetChild("Text_BaoDi")

    usable=obj:GetController("usable");
    wishList = obj:GetChild("WishList")
    ctClickBoxReward=obj:GetController("ClickBoxRewards")
    btnCloseReward=obj:GetChild("Btn_CloseReward")
    btnOpenTips=obj:GetChild("Btn_OpenTips")
    ctBox=btnDrawBox:GetController("Type")

    aniRightOut = obj:GetTransition("RightToLeft1");
    aniRightIn = obj:GetTransition("RightToLeft2");
    aniLeftOut = obj:GetTransition("LeftToRight1");
    aniLeftIn = obj:GetTransition("LeftToRight2");
    ctrlBanClick=obj:GetController("BanClick")

    chooseText.text=getLanguage("Draw_TargetDraw_Btn_ChangeHero");
    seleText.text=getLanguage("Draw_TargetDraw_Btn_SelectHero");
    btnChangeOccupationtitle.text=getLanguage("Draw_OccupationDraw_Btn_ChangeOccupation");
    HeroTypetitle1.text=getLanguage("Draw_OccupationDraw_Rule1");
    HeroTypetitle2.text=getLanguage("Draw_OccupationDraw_Rule2");
    btnSeletOccupationtitle.text=getLanguage("Draw_OccupationDraw_Btn_SelectOccupation");
    cash.text = "0";
    coin.text = "0";
    ctrlBanClick.selectedIndex=0
    wishBnt = obj:GetChild("Btn_WishList")
    wishCtrl = obj:GetController("Wish")
    wishHeroList = {}
    allCount = logicMgr.HeroManager.GetWishNum()
    globalWish = decodeJsonStrToTabel(G.dataTable["t_global"]["558"].f_string_value);
    for i=1,2 do
         local hero = obj:GetChild("WishHero"..i)
         local item = {}
         item["headItem"] = hero:GetChild("hero")
         item["heroCtrl"] = hero:GetController("state")
        item["obj"] = hero
         wishHeroList[i] = item
    end
--not have thisKey:Draw_OccupationDraw_Btn_ChangeOccupation	
    this.colorObj = Color.New(1, 1, 1, 1);
    resTab = {}
    for i, v in pairs(G.dataTable["t_drawpool"]) do
        if v.f_1DrawConsume ~= "" then
            resTab[tonumber(v.f_DrawPoolID)] = decodeJsonStrToTabel(v.f_1DrawConsume)[1];
        end
    end
    cards[1] = obj:GetChild("Btn_CardMid");
    cards[2] = obj:GetChild("Btn_CardRight");
    cards[3] = obj:GetChild("Btn_CardLeft");
    this.midCardIcon = cards[1]:GetChild("icon");
    this.midCardFrame = cards[1]:GetChild("frame");
    this.midCardSpineList = {};
    this.OccupationList={};
    for i = 1, 3 do
        table.insert(this.midCardSpineList, cards[1]:GetChild("Graph_Spine"..i));
    end
    for i = 1, 2 do
        table.insert(this.OccupationList, cards[1]:GetChild("Graph_Occupation"..i));
    end
      shopHandler.reqShopDataList(SHOP_ID);
    btn_DrawTen.text="召唤10次";
    --table.insert(resTab, decodeJsonStrToTabel(G.dataTable["t_drawpool"]["1"].f_1DrawConsume)[1])
    --table.insert(resTab, decodeJsonStrToTabel(G.dataTable["t_drawpool"]["2"].f_1DrawConsume)[1])
    --table.insert(resTab, 1)--decodeJsonStrToTabel(G.dataTable["t_drawpool"]["2"].f_1DrawConsume)[1]
    --table.insert(resTab, decodeJsonStrToTabel(G.dataTable["t_drawpool"]["4"].f_1DrawConsume)[1])
    this.addEvent();
    drawHandler.ReqHeroInfo()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.DrawPond, false) then
        this.wishEffect.selectedIndex = 1;
    else
        this.wishEffect.selectedIndex = 0;
    end
    this.data=G.dataTable["t_global"][tostring(316)]["f_string_value"]
    --this.updatePage();
    buyTime = 0;
    this.Refreshres();
    drawHandler.IsAskProcess=true
    drawHandler.SendDrawProcessInfo()
    this.InitDrawBoxTable()
    this.SetCurPool();
    drawHandler.GoReqSendWishInfoMessage();
    -- UIRedDots.addViewListen(PanelResNames.UIDraw, PanelNames.UIDraw.."btnWish", btnWish, Config.RedDotsType.DrawPond, 10);
    UIRedDots.addViewListen(PanelResNames.UIDraw, PanelNames.UIDraw.."btnWish", btnWish, Config.RedDotsType.DrawPond, {1, 10});
    UIRedDots.addViewListen(PanelResNames.UIDraw, PanelNames.UIDraw.."btn_draw_wish", wishBnt, Config.RedDotsType.drawWishList, 10);
    this.modelList = {}

    -- 免费单抽相关
    local uiTxtFree = btn_DrawOne:GetChild("title2")
    if uiTxtFree ~= nil then
        uiTxtFree.text = getLanguage("Draw_FreeText1")
    end
    mDiamondSummonState = SUMMON_STATE.Normal
    -- this.showFreeSummonTime()
end

function UIDraw.UpdateWishData()
    local value = tonumber(GetPlayerPrefs("wishToggle"))
    if  logicMgr.HeroManager.WishIsGet() then
        if (not value) or (value and value == 1) then
            btnToggle.selected = true
            this.onlyTenCtrl.selectedIndex = 1
        else
            this.onlyTenCtrl.selectedIndex = 0
            btnToggle.selected = false
        end
        wishIndex = logicMgr.HeroManager.extraNum > #globalWish and #globalWish or logicMgr.HeroManager.extraNum
        hasHeroIds = logicMgr.HeroManager.extraHasHeroIds
        wishIds = clone(logicMgr.HeroManager.extraHeros)
        this.selectHeroCtrl.selectedIndex = 1
        notLimitHeroList.itemRenderer = this.RenderItem
        this.wishHerosList = G.dataTable["t_global"]["556"].f_string_value;
        this.typeCtrl.selectedIndex = 6
        this.SetOneHero(this.noLimitHero_1,wishIds[1])
        this.SetOneHero(this.noLimitHero_2,wishIds[2])
        wishTips.text = string.format(getLanguage("Draw_WishList_Tips20"),logicMgr.HeroManager.GetInsureRemain())
        btnToggle.title = getLanguage("Draw_WishList_Tips21")
    else
        this.selectHeroCtrl.selectedIndex = 0
        SetPlayerPrefs("wishToggle",1)
        this.onlyTenCtrl.selectedIndex = 0
        btnToggle.selected = false
    end
    this.initPapers();

    -- 免费单抽数据刷新
    this.showFreeSummonTime()
end

function UIDraw.OnJobChanged()
    this.typeHeros = {}
    local type = this.typeCtrl.selectedIndex
    if type ~= 6 then
        for _,v in ipairs(this.wishHerosList) do
            local itemValue = logicMgr.HeroManager.getHeroDatabyModelId(v,true)
            if itemValue.type == type + 1  then
                table.insert(this.typeHeros,v)
            end
        end
    else
        this.typeHeros = this.wishHerosList
    end
    this.notLimitHeroList.numItems = #this.typeHeros
end

function UIDraw.SetOneHero(obj,data)
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    local ctrl = obj:GetController("state")
    local obj_hero = obj:GetChild("hero")
    if data and data ~= 0 then
        if ctrlItem then
            if hasHeroIds[1]==data or hasHeroIds[2]==data then
                ctrl.selectedIndex = 2
            else
                ctrl.selectedIndex = 1
            end
            local h = logicMgr.HeroManager.getHeroDatabyModelId(tostring(data))
            ctrlItem.initData(obj_hero, h,true,nil,nil,nil,nil,nil,true);
        end
    else
        ctrl.selectedIndex = 0
    end
end

function UIDraw.WishSure()
    drawHandler.ReqWishHeroData(logicMgr.HeroManager.GetWishData(),wishIds)
    this.noLimitCtrl.selectedIndex = 0
    showUI(PanelNames.UIBottom,true)
end

function UIDraw.ClickItem(index)
    closeUI(PanelNames.UIBottom)
    this.noLimitCtrl.selectedIndex = 1
    if index then
        if hasHeroIds[1]~=wishIds[index] and hasHeroIds[2]~=wishIds[index] then
            wishIds[index] = 0
            if index == 1 then
                this.SetOneHero(noLimitHero_1,wishIds[index])
            else
                this.SetOneHero(noLimitHero_2,wishIds[index])
            end
        end
    end
    if #this.typeHeros ==0 then
        this.OnJobChanged()
    end
    this.notLimitHeroList.numItems = #this.typeHeros
end

function UIDraw.RenderItem(index,itemobj)
    local hid = this.typeHeros[index+1]
    local itemValue = logicMgr.HeroManager.getHeroDatabyModelId(hid)
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    if charactor ~= nil then
        charactor.initData(itemobj, itemValue,true,nil,nil,nil,nil,nil,true);
    end
    local ctr_level = itemobj:GetController("isShowLevel")
    ctr_level.selectedIndex = 1
    local gouCtrl = itemobj:GetController("ctrlHadBattle")
    if hid == wishIds[1] or hid == wishIds[2] then
        gouCtrl.selectedIndex = 1
    else
        gouCtrl.selectedIndex = 0
    end
    itemobj.onClick:Clear()
    itemobj.onClick:Add(function ()
        if gouCtrl.selectedIndex == 0 then
            if  wishIds[1] ~= 0 and  wishIds[2] ~= 0 then
                UISysTips.AddMsg("至多选择两个英雄")
                return
            end
            gouCtrl.selectedIndex = 1
            if wishIds[1]==0 then
                wishIds[1] = hid
                this.SetOneHero(this.noLimitHero_1,hid)
            else
                wishIds[2] = hid
                this.SetOneHero(this.noLimitHero_2,hid)
            end
        else
            if hasHeroIds[1]==hid or hasHeroIds[2]==hid then
                UISysTips.AddMsg(getLanguage("Draw_WishList_Tips22"))
                return
            end
            gouCtrl.selectedIndex = 0
            if hid == wishIds[1] then
                wishIds[1] = 0
                this.SetOneHero(this.noLimitHero_1,0)
            else
                wishIds[2] = 0
                this.SetOneHero(this.noLimitHero_2,0)
            end
        end
    end)
end

function UIDraw.SetWishData()
    if allCount>= G.dataTable["t_global"]["406"].f_int_value then
        wishCtrl.selectedIndex = 1
    else
        wishCtrl.selectedIndex = 0
    end
    local heroIds = logicMgr.HeroManager.GetWishData(true)
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    for i=1,2 do
        if heroIds and heroIds[i]~=0 then
            if logicMgr.HeroManager.WishIsGet(heroIds[i]) then
                wishHeroList[i]["heroCtrl"].selectedIndex = 2
            else
                wishHeroList[i]["heroCtrl"].selectedIndex = 1
            end
            local itemValue = logicMgr.HeroManager.getHeroDatabyModelId(heroIds[i])
            if charactor ~= nil then
                charactor.initData(wishHeroList[i]["headItem"], itemValue,true,nil,nil,nil,nil,nil,true);
            end
        else
            wishHeroList[i]["heroCtrl"].selectedIndex = 0
        end
    end
    UIDraw.checkChangeTips()
end

function UIDraw.InitDrawBoxTable()
    this.drawBoxTable={}
    for i,v in pairs(G.dataTable["t_drawbox"])do
        table.insert(this.drawBoxTable,v)
    end
    table.sort(this.drawBoxTable,function(a,b)
        return a.f_Id<b.f_Id
    end)
    this.InitProgressTable()
end
function UIDraw.InitProgressTable()
    this.progressTable={}
    this.progressTable.normal={}
    this.progressTable.last={}
    --this.progressTable.last.loop={}

    --除了最后一个之外
    local normal={}
    for i=1,#this.drawBoxTable-1 do
        local info={}
        local rewards=this.drawBoxTable[i].f_DrawBoxReward
        if i==1 then
            info.loopNum=this.drawBoxTable[i].f_DrawNum/(rewards[#rewards][1])
        else
            info.loopNum=(this.drawBoxTable[i].f_DrawNum-this.drawBoxTable[i-1].f_DrawNum)/rewards[#rewards][1]
        end
        info.oneLoop={}
        for k=1,#rewards do
            local max
            if k==1 then
                max=rewards[1][1]
            else
                max=rewards[k][1]-rewards[k-1][1]
            end
            table.insert(info.oneLoop,max)
        end
        table.insert(normal,info)
    end
    for i,v in ipairs(normal)do
        for k=1,v.loopNum do
            for a,b in ipairs(normal[i].oneLoop)do
                table.insert(this.progressTable.normal,b)
            end
        end
    end
    --最后一个为-1的无限循环区间特殊处理
    local reward=this.drawBoxTable[#this.drawBoxTable].f_DrawBoxReward
    for i=1,#reward do
        local max
        if i==1 then
            max=reward[1][1]
        else
            max=reward[i][1]-reward[i-1][1]
        end
        table.insert(this.progressTable.last,max)
    end
    this.CalculateProgress(70,350)
    this.CalculateProgress(100,900)
end
function UIDraw.initPool()

end

function UIDraw.Refreshres()
    dirnum = logicMgr.ItemManager.getBagNumByTableID(200004);
    occupationnum=logicMgr.ItemManager.getBagNumByTableID(200003);
    occuTipsnum=logicMgr.ItemManager.getBagNumByTableID(200006);
    
    RefreshBtn();
end
function UIDraw.RefreshBtn()
  
    btn_DrawOne.onClick:Clear();
    btn_DrawTen.onClick:Clear();
    if  tonumber(showTab[1])==6 then   
        resource.text=dirnum;
        iconresource.url="ui://ItemAtlas/".."200004";
        if dirnum<=0  then
            this.SetBtn(false,this.ChangeOnclick)
        else
            this.SetBtn(true)
        end  
    elseif this.curisHerotype then
        resource.text=occuTipsnum;
        iconresource.url="ui://ItemAtlas/".."200006";
        if occuTipsnum<=0  and occupationnum<=0  then     
           -- this.SetBtn(false,this.ChangeOnclickOcc)
           this.SetBtn(true)
        else
            this.SetBtn(true)
        end
    else
        this.SetBtn(true)
    end
end
function UIDraw.SetBtn(flag,callback)
    --if flag then
    --    Util.LogError("Set Btn:true")
    --else
    --    Util.LogError("Set Btn:false")
    --end
    local enityone=btn_DrawOne:GetChild("Com_SaoGuang");
    local enityTen=btn_DrawTen:GetChild("Com_SaoGuang");
    if flag then
        usable.selectedIndex=0;  
        btn_DrawOne.onClick:Add(this.onClickDrawOne);
        btn_DrawTen.onClick:Add(this.onClickDrawTen); 
    else
        usable.selectedIndex=1;  
        btn_DrawOne.onClick:Add(callback);
        btn_DrawTen.onClick:Add(callback);
    end
    redDotsten.visible=flag;
    enityone.visible=flag;
    enityTen.visible=flag;

end

function UIDraw.ChangeOnclick()
    UISysTips.AddMsg(getLanguage("Sys_MsgTargetDraw_NoItem"));
end

function UIDraw.ChangeOnclickOcc()
    UISysTips.AddMsg("职业标记不足，无法进行召唤");
end

function UIDraw.updateAll()
    this.ClickPage();
end
function UIDraw.OnMoveStart(evt)
    startDragPosX = evt.inputEvent.x;
end

function UIDraw.OnEndMove(evt)
    if evt and startDragPosX then
        AudioManager.Play(1028)
        local endX = evt.inputEvent.x;
        if endX > startDragPosX and math.abs(endX - startDragPosX) > 100 then
            this.scrollToLast();
        elseif startDragPosX > endX and math.abs(startDragPosX - endX) > 100 then
            this.scrollToNext();
        end
        startDragPosX = nil;
    end
end

function UIDraw.updateRes()
    cash.icon = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(resTab[tonumber(curPoolId)])].f_Icon;
    coin.icon = "ui://ItemAtlas/" .. CurrencyEnum.GOLD;
    cash.text = getNumString(this.getDrawResNum(resTab[tonumber(curPoolId)]));
    coin.text = this.getDrawResNum(CurrencyEnum.GOLD);
    UIHeadMenu.cashId = resTab[tonumber(curPoolId)];
    UIHeadMenu.coinId = CurrencyEnum.GOLD;
end
function UIDraw.addProgressEvent()
    btnOpenTips.onClick:Add(function()
        ctClickBoxReward.selectedIndex=1
    end)
    btnCloseReward.onClick:Add(function ()
        ctClickBoxReward.selectedIndex=0
    end)
    wishHeroList[1]["obj"].onClick:Add(function()
        showUI(PanelNames.UIDrawWishList)
    end)
    wishHeroList[2]["obj"].onClick:Add(function()
        showUI(PanelNames.UIDrawWishList)
    end)
end
function UIDraw.GetProgressData(drawNum)
    local cfg=this.drawBoxTable
    local index=#cfg
    for i,v in ipairs(cfg)do
        if v.f_DrawNum>drawNum or v.f_DrawNum==-1 then
            index=i
            break
        end
    end
    local base=0
    if index>1 then
        base=cfg[index-1].f_DrawNum
    end
    local rewards=cfg[index].f_DrawBoxReward
    local offset=drawNum-base
    local loopNum=rewards[#rewards][1]
    local res=offset-math.floor(offset/loopNum)*loopNum
    local start=1
    local nowNum=res
    local temp=0
    local needDraw=rewards[1][1]
    for i,v in ipairs(rewards)do
        if res<v[1] then
            needDraw=v[1]-temp
            break
        end
        temp=v[1]
        start=start+1
        nowNum=res-v[1]
    end
    local desc=getLanguage("DrawBoxDesc2")
    local boxName=getLanguage("DrawBoxName"..index)
    if index~=#cfg then
        local nextBoxName=getLanguage("DrawBoxName"..index+1)
        desc=string.format(getLanguage("DrawBoxDesc1"),cfg[index].f_DrawNum-drawNum,nextBoxName)
    end
    local itemId=rewards[start][2]
    local itemNum=rewards[start][3]
    local ans={}
    ans.itemId=itemId
    ans.itemNum=itemNum
    ans.nowNum=nowNum
    ans.needDraw=needDraw
    ans.desc=desc
    ans.resNeed=needDraw-nowNum
    ans.index=index-1
    ans.boxName=boxName
    return ans
end
function UIDraw.CalculatePos(drawNum)
    local cfg=this.drawBoxTable
    local turnNums={}
    for i=1,#cfg-1 do
        local rewards=cfg[i].f_DrawBoxReward
        local turnNum
        local num
        if i==1 then
            turnNum=cfg[i].f_DrawNum/(rewards[#rewards][1])
        else
            turnNum=(cfg[i].f_DrawNum-cfg[i-1].f_DrawNum)/rewards[#rewards][1]
        end
        num =#rewards
        table.insert(turnNums,{ turnNum, num })
    end

    local ans=0
    for i,v in ipairs(cfg)do
        if v.f_DrawNum>drawNum or v.f_DrawNum==-1 then
            local reward=v.f_DrawBoxReward
            local oneTurnSum=reward[#reward][1]
            local temp
            if i==1 then
                temp=drawNum
            else
                temp=drawNum-cfg[i-1].f_DrawNum
            end
            local order=math.floor(temp/oneTurnSum)
            local t=temp-order*oneTurnSum
            local pos=1
            for x=1,#reward do
                if t<reward[x][1] then
                    pos=x
                    break
                end
            end
            ans=ans+(#reward*order+pos)
            break
        else
            ans=ans+turnNums[i][1]*turnNums[i][2]
        end
    end
    return ans
end
function UIDraw.CalculateProgress(lastDraw,nowDraw)
    local pos1=this.CalculatePos(lastDraw)
    local pos2=this.CalculatePos(nowDraw)
    local turn={}
    if pos1==0 or pos2==0 or pos1>=pos2 then
        return {}
    else
        local normal=this.progressTable.normal
        local normalNum=#normal
        local last=this.progressTable.last
        local lastNum=#last
        if pos1<=normalNum and pos2<=normalNum then
            for i=pos1+1,pos2 do
                table.insert(turn,normal[i])
            end
        elseif pos1<=normalNum and pos2>normalNum then
            for i=pos1+1,normalNum do
                table.insert(turn,normal[i])
            end
            local index=1
            for i=1,pos2-normalNum do
                table.insert(turn,last[index])
                index=index+1
                if index>lastNum then
                    index=1
                end
            end
        else    --两者都大于normalnum
            local index=(pos1+1-normalNum)%lastNum
            if index==0 then
                index=lastNum
            end
            for i=1,pos2-pos1 do
                table.insert(turn,last[index])
                index=index+1
                if index>lastNum then
                    index=1
                end
            end
        end
    end
    return turn
end
function UIDraw.removeProgressEvent()
    btnOpenTips.onClick:Clear()
    btnCloseReward.onClick:Clear()
    wishHeroList[1]["obj"].onClick:Clear()
    wishHeroList[2]["obj"].onClick:Clear()
end
function UIDraw.ManageProcessMessage(msg)
    logicMgr.HeroManager.total_draw_count = msg.totalDrawCount
    if msg.haveReward==0 then
        this.updateProgressAndReward(msg.totalDrawCount)
    end
end
function UIDraw.updateProgressAndReward(num)
        local ans=this.GetProgressData(num)
        ctBox.selectedIndex=ans.index
        txtDesc.text=ans.desc
        barDraw.max=ans.needDraw
        barDraw.value=ans.nowNum
        txtDrawBox.text=ans.boxName
        boxRewardsList:RemoveChildrenToPool()
        local item = boxRewardsList:AddItemFromPool();
        local itemController = CtrlManager.GetCtrl(PanelNames.Item);
        if itemController ~= nil then
            local data=logicMgr.ItemManager.getItemConstDatabyModelId(ans.itemId)
            data.num=ans.itemNum
            itemController.initData(item,data);
        end
        lastDrawNum=num

        TAManager.UserSet("draw_box_process", num)
end
function UIDraw.WatchDrawProgress()
    --播放动画
    local num=drawHandler.drawNum
    if num==nil or num==0 or num==lastDrawNum then
        return
    end
    ctrlBanClick.selectedIndex=1
    local maxTable=this.CalculateProgress(lastDrawNum,num)
    local value=this.GetProgressData(num).nowNum
    local function endCB()
        this.ProgressCB(num)
    end
    local function tweenCB()

    end
    this.Tweeners= PlaySliderAnim(barDraw,value,maxTable,this.Tweeners,endCB,tweenCB)
end
function UIDraw.ProgressCB(num)
    ctrlBanClick.selectedIndex=0
    --清除动画产生tween
    this.updateProgressAndReward(num)
    if drawHandler.dpRewards and #drawHandler.dpRewards>0 then
        showUI(PanelNames.UICommonDrawItemGet,EnumConst.DrawResultType.ProgressAward,{progressAwards=drawHandler.dpRewards})
    end
    drawHandler.ClearDpReward()
end
function UIDraw.addEvent()
    --Util.LogError("Add Event")
    cards[1].onTouchBegin:Add(this.OnMoveStart);
    cards[1].onTouchEnd:Add(this.OnEndMove);
    --LuaBehaviour:AddClick(btn_Prev.gameObject,this.onClickPrevPage);
    --LuaBehaviour:AddClick(btn_Next.gameObject,this.onClickNextPage);
    btn_SelectHero.onClick:Add(this.OpenSelectHero);
    --btn_ture.onClick:Add(this.CloseHero);
    ChooseBtn.onClick:Add(this.OpenSelectHero);
    btnChangeOccupation.onClick:Add(this.OpenSelectHeroType);
    btnSeletOccupation.onClick:Add(this.OpenSelectHeroType);
    btnSource.onClick:Add(this.onClickSource);
    btnresource.onClick:Add(this.onClickSource);
    btnLast.onClick:Add(this.scrollToLast);
    btnNext.onClick:Add(this.scrollToNext);
    btnLook.onClick:Add(this.onClickInformation);
    btn_DrawOne.onClick:Add(this.onClickDrawOne);
    btn_DrawTen.onClick:Add(this.onClickDrawTen);
    btn_Shop.onClick:Add(this.onClickShop);
    --content.onClickItem:Add(this.scrollToItem);
    btnWish.onClick:Add(this.OpenWish);
    wishBnt.onClick:Add(this.ShowWish)
    btn_Sure.onClick:Add(this.WishSure)
    btnToggle.onClick:Add(function()
        if btnToggle.selected then
            SetPlayerPrefs("wishToggle",1)
            this.onlyTenCtrl.selectedIndex = 1
        else
            SetPlayerPrefs("wishToggle",0)
            this.onlyTenCtrl.selectedIndex = 0
        end
        this.updatePage()
    end)
    this.noLimitheroCom.onClick:Add(function()
        this.ClickItem()
    end)
    this.noLimitHero_1.onClick:Add(function()
        this.ClickItem(1)
    end)
    this.noLimitHero_2.onClick:Add(function()
        this.ClickItem(2)
    end)
    this.typeCtrl.onChanged:Add(this.OnJobChanged)
    --btn_head.onClick:Add(this.onClickHead);
    this.addProgressEvent()
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIDraw, Config.FuncOpenType.DrawPond, btnWish.name, btnWish);

    ListenEvent(Config.EventType.DrawBuySuccess, this.buySuccessDraw)

    ListenEvent(Config.EventType.Fresh_Draw, this.updateAll)
    ListenEvent(Config.EventType.Fresh_Currency, this.updatePage);
    ListenEvent(Config.EventType.Fresh_Bag, this.updatePage);
    ListenEvent(Config.EventType.Fresh_Shop, this.BuySecondTime)
    ListenEvent(Config.EventType.Fresh_SelectHero, this.SetSelectHero)
    ListenEvent(Config.EventType.Fresh_AppointDrawInfo, this.SetPoolMes)
    ListenEvent(Config.EventType.Fresh_DrawProcess, this.ManageProcessMessage)
    ListenEvent(Config.EventType.Fresh_Drenum, this.Refreshres)
    ListenEvent(Config.EventType.Fresh_OccDraw,this.GetOcchero);
    ListenEvent(Config.EventType.WatchDrawProgress,this.WatchDrawProgress);
    ListenEvent(Config.EventType.Draw_Wish_list_Update,this.SetWishData)
    ListenEvent(Config.EventType.UpdateWishHeroData,this.UpdateWishData)
end


function UIDraw.removeEvent()
    --Util.LogError("remove Event")
    --LuaBehaviour:RemoveClick(btn_Prev.gameObject);
    --LuaBehaviour:RemoveClick(btn_Next.gameObject);
    btn_SelectHero.onClick:Remove(this.OpenSelectHero);
    --btn_ture.onClick:Remove(this.CloseHero);
    ChooseBtn.onClick:Remove(this.OpenSelectHero);
    btnChangeOccupation.onClick:Remove(this.OpenSelectHeroType);
    btnSeletOccupation.onClick:Remove(this.OpenSelectHeroType);
    btnSource.onClick:Remove(this.onClickSource);
    btnresource.onClick:Remove(this.onClickSource);
    btnLast.onClick:Remove(this.scrollToLast);
    btnNext.onClick:Remove(this.scrollToNext);
    btnLook.onClick:Remove(this.onClickInformation);
    btn_DrawOne.onClick:Remove(this.onClickDrawOne);
    btn_DrawTen.onClick:Remove(this.onClickDrawTen);
    btn_Shop.onClick:Remove(this.onClickShop);
    btnWish.onClick:Remove(this.OpenWish);
    wishBnt.onClick:Remove(this.ShowWish)
    this.noLimitheroCom.onClick:Clear()
    this.noLimitHero_1.onClick:Clear()
    this.noLimitHero_2.onClick:Clear()
    btnToggle.onClick:Clear()
    btn_Sure.onClick:Remove(this.WishSure)
    this.typeCtrl.onChanged:Remove(this.OnJobChanged)
    --content.onClickItem:Remove(this.scrollToItem);
    --btn_head.onClick:Remove(this.onClickHead);
    UIRedDots.removeViewEvent(PanelResNames.UIDraw)
    --UIRedDots.removeViewEvent(PanelResNames.UIDrawPond);

    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIDraw);

    CloseEvent(Config.EventType.Fresh_Draw, this.updateAll)
    CloseEvent(Config.EventType.Fresh_Currency, this.updatePage);
    CloseEvent(Config.EventType.Fresh_Bag, this.updatePage);
    CloseEvent(Config.EventType.Fresh_Shop, this.BuySecondTime);
    CloseEvent(Config.EventType.DrawBuySuccess, this.buySuccessDraw);
    CloseEvent(Config.EventType.Fresh_SelectHero, this.SetSelectHero)
    CloseEvent(Config.EventType.Fresh_AppointDrawInfo, this.SetPoolMes)
    CloseEvent(Config.EventType.Fresh_DrawProcess, this.ManageProcessMessage)
    CloseEvent(Config.EventType.Fresh_Drenum, this.Refreshres)
    CloseEvent(Config.EventType.Fresh_OccDraw,this.GetOcchero);
    CloseEvent(Config.EventType.WatchDrawProgress,this.WatchDrawProgress);
    CloseEvent(Config.EventType.Draw_Wish_list_Update,this.SetWishData)
    CloseEvent(Config.EventType.UpdateWishHeroData,this.UpdateWishData)
end

function UIDraw.ShowWish()
    if this.spineIsIning then
        return;
    end
    drawHandler.ReqHeroInfo()
    showUI(PanelNames.UIDrawWishList)
end
-- function UIDraw.SetOcchero(hero1,hero2)
--     drawHandler.SendSetVocationDrawHero(hero1,hero2);
-- end

function UIDraw.GetOcchero(hero1,hero2)
    if hero1~=0 and hero2~=0  then
        this.occhero1=hero1;
        this.occhero2=hero2;
        HeroTypeIcon1.url="ui://ICONAtlas/"..EnumConst.HeroTypeIcon[hero1];
        HeroTypeIcon2.url="ui://ICONAtlas/"..EnumConst.HeroTypeIcon[hero2];
        isoccupation=true;
        local value=this.GetHeroShowByType(this.occhero1,this.occhero2)
        this.heroshowTab=value.f_HeroShow;
        tab_top[3]=value.f_DrawPoolID;
        this.initPapers(); 
    end
    
end

function UIDraw.OpenSelectHero()
    showUI(PanelNames.UIDrawChooseHero,this.GetAppointHeroList(),selecthero);
end
function UIDraw.GetAppointHeroList()
    if this.appointHeroList == nil then
        this.appointHeroList = {};
        local data = this.data;
        local removeHero = logicMgr.ActiveManager.RemoveHeroIds();
        local removeIndex = -1;
        for k,v in pairs(data) do
            removeIndex = -1;
            for rk, rv in pairs(removeHero) do
                if tonumber(v) == tonumber(rv) then
                    --table.remove(removeHero, rk);
                    removeIndex = rk;
                    break;
                end
            end
            if removeIndex == -1 then
                table.insert(this.appointHeroList, v);
            else
                table.remove(removeHero, removeIndex);
            end
        end
    end
    return this.appointHeroList;
end
function UIDraw.OpenSelectHeroType()
    showUI(PanelNames.UIDrawChangeOccupation,this.occhero1,this.occhero2);
end

function UIDraw.SetPoolMes(msg)
    UIDraw.SetSelectHero(msg.selectHeroID);
end

function UIDraw.SetSelectHero(heroId)
    local curHeroData = logicMgr.HeroManager.getHeroDatabyModelId(tostring(heroId),true);
    if  heroId and heroId~=0 then
        Heroname.text=curHeroData.name;
        selecthero=tostring(heroId);
        isdirecting=true;
        this.initPapers();    
    end
end

function UIDraw.OpenWish()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.DrawPond, true,btnWish) then
        title.visible = false;
        showUI(PanelNames.UIDrawPond, function()
            title.visible = true
        end);
    end
end

function UIDraw.buySuccessDraw()
    if curDrawInfo ~= nil then
        this.confirmDraw(curDrawInfo);
        curDrawInfo = nil;
    end
end

function UIDraw.OnDestroy()
    if this.drawOutTime ~= nil then
        utimer.remove(this.drawOutTime)
        this.drawOutTime = nil
    end
    if this.drawInTime ~= nil then
        utimer.remove(this.drawInTime)
        this.drawInTime = nil
    end

    this.removeEvent();
    for key, value in pairs(this.drawWrappers) do
        if not HelperFunc.IsNull(value) then
            value:Dispose()
        end
    end
    this.drawWrappers = {};
    for key, value in pairs(this.spineSprine) do
        destroy(value)
    end
    this.spineSprine = {};

    -- 移除计时器
    this.removeFreeSummonTimer()
    
    HelperFunc.UnloadLihui()
end

function UIDraw.SetCurPool()
    if this.SetcurpooId~=nil then 
        for key, value in pairs(this.tab_top) do
            if this.SetcurpooId==value then
                curpage=key;
            end
        end
    --    curpage=this.SetcurpooId;
        if curpage==3 then
            -- body
            this.curisHerotype=true;
        else
            this.curisHerotype=false;
        end
    end
end

function UIDraw.OnEnable()
    --召唤界面背景音乐
    this.isGuiding = false;
    allCount = logicMgr.HeroManager.GetWishNum()
    if logicMgr.GuideMgr.IsGuiding() and GuideMgr.GetGuideID() == 2301 then
        this.isGuiding = true;
    end
    buyTime = 0;
    --local mapId = logicMgr.MapManager.getMapId(); -- 应策划要求,把定向召唤干掉
    --if mapId>=this.dirstage then
    --    tab_top={"1","2","3","6"};
    --else
    --    tab_top={"1","2","3"};    --应策划要求,把职业召唤干掉
        tab_top={"1","2"};
    --end
    this.curisHerotype=false;
    drawHandler.sendReqPoolMessage(tab_top)
    --closeUI(PanelResNames.UIHeadMenu);
end

function UIDraw.OnDisable()
    buyTime = 0;
    --choosehero.selectedIndex=0;
    FireEvent(Config.EventType.Fresh_Currency);
    --HelperFunc.UnloadUnusedAssets(EnumConst.ClearType.Prefab)
    --if not isOpenUI(PanelResNames.UIHeadMenu) then
    --    --showUI(PanelNames.UIHeadMenu)
    --else
    --    UIHeadMenu.Init();
    --end
    FireEvent(Config.EventType.Close_Draw_Panel);
    KillAllTweeners(this.Tweeners)
    this.appointHeroList = nil
end

--[[
function UIDraw.onClickPrevPage()
    curpage = curpage - 1;
    if curpage < 1 then
        curpage = #tab_top;
    end
    --activityPage.transform:DOLocalMoveX((curpage-1)*-720-360,0.4,false);   ---720*(curpage-2)
    this.ClickPage();
end
]]

--[[function UIDraw.onClickNextPage()
    curpage = curpage + 1;
    if curpage > #tab_top then
        curpage = 1;
    end
    --activityPage.transform:DOLocalMoveX((curpage-1)*-720-360,0.4,false);
    this.ClickPage();
end]]

function UIDraw.onClickChangePage(index)
    --local go = Data.data;
    --local index = content:GetChildIndex(go);
    --curpage = index + 1;
    --if curpage > #tab_top then
    --    curpage = 1;
    --end
    this.ClickPage();
end
--
--function UIDraw.onClickHead()
--    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RoleInfo, true) then
--        showUI(PanelNames.UIHeadInfo);
--    end
--end

function UIDraw.onClickInformation()
    showUI(PanelNames.UIDrawProbability, curPoolId);
    
end

function UIDraw.onClickDrawOne()
    --if not UIDraw.btnDownState then
    --    UIDraw.btnDownState = true;
    --end
    this.drawSkills(1);
end

function UIDraw.onClickDrawTen()
    --if not UIDraw.btnDownState then
    --end
    --    UIDraw.btnDownState = true;
    this.drawSkills(10);
    --Util.LogError("drawten")
end

function UIDraw.onClickShop()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroShop, true,btn_Shop) then
        showUI(PanelNames.UIShop, EnumConst.ShopType.heroShop, function()
            shopHandler.reqShopDataList(11000);
        end, 6); -- 6-召唤界面背景音乐
    end
end

function UIDraw.initPapers()
    --local idx = 0
    --for i = 1, 3 do
    --    idx = idx == 0 and curpage or idx + 1;
    --    if #tab_top >= idx then
    --        showTab[i] = tab_top[idx];
    --    else
    --        idx = 1;
    --        showTab[i] = tab_top[1];
    --    end
    --end
    showTab[1] = tab_top[tonumber(curpage)];
    showTab[2] = tab_top[tonumber(curpage) - 1 <= 0 and #tab_top or tonumber(curpage) - 1];
    showTab[3] = tab_top[tonumber(curpage) + 1 > #tab_top and 1 or tonumber(curpage) + 1];
    -- 临时写法,等UI稳定了,可以把这个提出来. 2021-4-23 20:16:25
    for i = 1, 1 do
        this.initTop(i, cards[i]);
    end
    --content:SetVirtualAndLoop();
    --content.itemRenderer = this.initTop;
    --content.numItems = #tab_top;
    --content.scrollPane.onScroll:Add(this.doSpecialEffect);
    --content.scrollPane.onScrollEnd:Add(this.onScrollEnd);
    --this.doSpecialEffect();
    --this.onScrollEnd();
    this.onClickChangePage();
end

function UIDraw:onClickSource()
    if tonumber(showTab[1])==6  then
        this:SetSource(200004)
        elseif this.curisHerotype then
            this:SetSource(200006)
    end
end

function UIDraw:SetSource(num)
  
    this.showSourceList = {num}
    if     this.showSourceList==nil then
        return;
    end
    this.showSourceController.selectedIndex = 1;
    logicMgr.ItemManager.setSourceStart("UIDraw", true);
    this.effectController.selectedIndex = 0;
    this:updateSource();
end


function UIDraw:updateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function ()
        
        this.showSourceController.selectedIndex = 0;
    end, function ()
        this.showSourceController.selectedIndex = 0;

        --(PanelNames.UIDraw);
    end );
    
end

function UIDraw.initTop(index, obj)
    --obj:SetPivot(0.5, 0.5);
    --local icon = obj:GetChild("icon");
    --local frame = obj:GetChild("frame");
    --local spineList = {};
    --for i = 1, 3 do
    --    table.insert(spineList, obj:GetChild("Graph_Spine"..i));
    --end
    Refreshres();
    local _dataTable = G.dataTable["t_drawpool"][tostring(showTab[index])];
    this.titleName.text = getLanguage(_dataTable.f_DrawPoolName);
    this.midCardFrame.url = "ui://UIDraw/summon_form_frame_" .. showTab[index];
    this.midCardIcon.url = "ui://UIDraw/summon_form_kp_" .. showTab[index];
    --local poolId = this.tab_top[tonumber(this.showTab[index])];
    --local redDosName = obj.asCom.id;
    --UIRedDots.removeListen(redDosName);
    --UIRedDots.addViewListen(PanelResNames.UIDraw, redDosName, obj, Config.RedDotsType.Summon, poolId, 10);
    if index == 1 then
        --printError("curpage======", curpage)
        local lastCofig = G.dataTable["t_drawpool"][tostring(showTab[2])];
        --if curpage-1==0 then
        --    btnLast.icon = "ui://UIDraw/summon_icon_zdzh06";
        --else
        --    btnLast.icon = "ui://UIDraw/summon_icon_zdzh0"..showTab[2]*2;
        --end
        btnLast.icon = "ui://UIDraw/"..lastCofig.f_DrawIcon;
        --printError("btnLast.icon======", btnLast.icon)
        btnLast.title = getLanguage(lastCofig.f_DrawPoolName);
        local redDosName = btnLast.asCom.id;
        UIRedDots.removeListen(redDosName);
        UIRedDots.addViewListen(PanelResNames.UIDraw, redDosName, btnLast, Config.RedDotsType.Summon, showTab[2], {1, 10});
        local nextCofig = G.dataTable["t_drawpool"][tostring(showTab[3])];
        --if curpage+1==3 then
        --    btnNext.icon = "ui://UIDraw/summon_icon_zdzh06";
        --else
        --    btnNext.icon = "ui://UIDraw/summon_icon_zdzh0"..showTab[3]*2;
        --end
        btnNext.icon = "ui://UIDraw/"..nextCofig.f_DrawIcon;
        btnNext.title = getLanguage(nextCofig.f_DrawPoolName);
        redDosName = btnNext.asCom.id;
        UIRedDots.removeListen(redDosName);
        UIRedDots.addViewListen(PanelResNames.UIDraw, redDosName, btnNext, Config.RedDotsType.Summon, showTab[3], {1, 10});
        if tonumber(showTab[1])==6 then
            -- body
            for i = 1, 3 do
                if this.spineSprine[i] ~= nil then
                    destroyImmediate(this.spineSprine[i]);
                end
            end
            if isdirecting then
                state.selectedIndex=2;
                this.spineSprine = {};
                local scale,location = HeroManager.GetHeroLocationResize(selecthero)
                local sprdata=G.dataTable["t_global"][tostring(357)]["f_string_value"]
                UIDraw.updateDraw(1, {selecthero, scale[1]*sprdata[1], scale[2]*sprdata[2], location[1]+sprdata[3], location[2]+sprdata[4]});
            else
                state.selectedIndex=1;
                this.spineSprine = {};
            end
        elseif this.curisHerotype then
            for i = 1, 3 do
                if this.spineSprine[i] ~= nil then
                    destroyImmediate(this.spineSprine[i]);
                end
            end
            if isoccupation then
                state.selectedIndex=4;                  
                this.spineSprine = {}; 
                for i = 1, #this.heroshowTab do
                    -- body
                    UIDraw.updateDraw(i+3, heroshowTab[i]);
                end
                
            else
                state.selectedIndex=3;
                this.spineSprine = {};
            end
            this.onlyTenCtrl.selectedIndex = 0
        else
            if tonumber(showTab[1]) == 2 then
                wishBnt.visible = false;
                wishCtrl.selectedIndex = 0
                noLimitCtrl.selectedIndex = 0
                selectHeroCtrl.selectedIndex = 0
                this.onlyTenCtrl.selectedIndex = 0
            else
                if allCount >= G.dataTable["t_global"]["406"].f_int_value then
                    wishCtrl.selectedIndex = 1
                else
                    wishCtrl.selectedIndex = 0
                end
                wishBnt.visible = true;
                if  logicMgr.HeroManager.WishIsGet() and curpage == 1 then
                    selectHeroCtrl.selectedIndex = 1
                    if btnToggle.selected then
                        this.onlyTenCtrl.selectedIndex = 1
                    else
                        this.onlyTenCtrl.selectedIndex = 0
                    end
                end
            end
            state.selectedIndex=0;
            for i = 1, 3 do
                if this.spineSprine[i] ~= nil then
                    destroyImmediate(this.spineSprine[i]);
                end
            end
            this.spineSprine = {};
            _dataTable.f_Spine = decodeJsonStrToTabel(_dataTable.f_Spine);
            for i = 1, 3 do
                local v = _dataTable.f_Spine[i];
                if #v > 0 then
                    UIDraw.updateDraw(i, v)
                end
            end    
        end

        
    end
end

function is_include(value, tab)
    for k, v in ipairs(tab) do
        if v == value then
            return true
        end
    end
    return false
end

function UIDraw.GetModelList()
    return this.modelList
end

function UIDraw.updateDraw(i, v)
    resMgr:LoadModelPrefab(logicMgr.HeroManager.GetHeroDrawingPath(v[1]), function(go)

        if not is_include(logicMgr.HeroManager.GetHeroDrawingPath(v[1]),this.modelList) then
            table.insert(this.modelList, logicMgr.HeroManager.GetHeroDrawingPath(v[1]))
        end

        if (this.drawWrappers[i] == nil) then
            this.drawWrappers[i] = GoWrapper.New();
        end
        if this.spineSprine[i] then
            destroyImmediate(this.spineSprine[i]);
        end
        if this.curisHerotype then
            this.CreatHeroShow(i-3,go,v,this.OccupationList);
           
        else
            this.CreatHeroShow(i,go,v,this.midCardSpineList);
        end
      
    end);
end

function UIDraw.CreatHeroShow(i,go,v,list)
    this.spineSprine[i] = newObject(go);
        this.spineSprine[i].name = "objHeroDraw"..i;
        this.spineSprine[i]:AddComponent(TCanvas);
        if this.spineIsIning then
            this.colorObj.a = 0;
            this.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj);
        else
            this.colorObj.a = 1;
            this.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj);
        end
        if this.curisHerotype then
           this.drawWrappers[i+3]:SetWrapTarget(this.spineSprine[i], false)
           Util.Lua_SetLocalPositionXYZ(this.spineSprine[i].transform, v[4], v[5], 0)
            Util.Lua_SetLocalScaleXYZ(this.spineSprine[i].transform, v[2], v[3], 1)
            list[i]:SetNativeObject(this.drawWrappers[i+3]);    
        else
            this.drawWrappers[i]:SetWrapTarget(this.spineSprine[i], false)
            Util.Lua_SetLocalPositionXYZ(this.spineSprine[i].transform, v[4], v[5], 0)
            Util.Lua_SetLocalScaleXYZ(this.spineSprine[i].transform, v[2], v[3], 1)
            list[i]:SetNativeObject(this.drawWrappers[i]);    
        end
        
        this.spineSprine[i]:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
         
end

function UIDraw.GetHeroShowByType(heroId1,heroId2)
    for key, value in pairs(this.HeroType) do
        local type1=value.f_HeroType[1];
        local type2=value.f_HeroType[2];
        if (heroId1==type1 and heroId2==type2) or (heroId1==type2 and heroId2==type1) then
            return value;
        end
    end
end

function UIDraw.doSpecialEffect()
    local midX = content.scrollPane.posX + content.viewWidth / 2;
    local chooseMid = (content:GetFirstChildInView() + 1) % content.numItems;
    --content:GetChildAt(chooseMid).sortingOrder = content:GetChildAt(chooseMid).sortingOrder - 9999;
    for i = 1, content.numChildren do
        local obj = content:GetChildAt(i - 1);
        local dist = math.abs(midX - obj.x - obj.width / 2);
        if dist > obj.width then
            obj:SetScale(0.8, 0.8);
        else
            local changeScale = 0.8 + (1 - dist / obj.width) * 0.2;
            obj:SetScale(changeScale, changeScale);
        end
        --if chooseMid < i then
        --    obj.sortingOrder = chooseMid - (chooseMid - i)
        --elseif chooseMid == i then
        --    obj.sortingOrder = chooseMid;
        --elseif chooseMid > i then
        --    obj.sortingOrder = chooseMid - (i - chooseMid);
        --
        --end
    end
    --if chooseMid ~= (content:GetFirstChildInView() + 1) % content.numItems then
    --    chooseMid = (content:GetFirstChildInView() + 1) % content.numItems;
    --    this.onClickChangePage(chooseMid);
    --end


end

--- 获取背包中的数量
function UIDraw.getDrawResNum(index)
    local num = 0
    if (index > 100) then
        num = logicMgr.ItemManager.getItemCountbyModelId(index); --itemHandler.GetNumByID(index);
    else
        num = logicMgr.ItemManager.getCurrencyCountByModelId(index);
    end
    return num
end

function UIDraw.ClickPage()
    --curPoolId = tab_top[curpage];
    --if (curPoolId == "4" and this.OpenState[4].open == 0) then
    --    if (this.OpenState[5].open == 1 and UIDrawProbability.curProfessionPage == 4) then
    --        UIDrawProbability.curProfessionPage = 5;
    --    end
    --    if (this.OpenState[6].open == 1 and UIDrawProbability.curProfessionPage == 4) then
    --        UIDrawProbability.curProfessionPage = 6;
    --    end
    --    if (this.OpenState[7].open == 1 and UIDrawProbability.curProfessionPage == 4) then
    --        UIDrawProbability.curProfessionPage = 7;
    --    end
    --    if (this.OpenState[8].open == 1 and UIDrawProbability.curProfessionPage == 4) then
    --        UIDrawProbability.curProfessionPage = 8;
    --    end
    --end
    this.updatePage();
end

function UIDraw.updatePage()
    curPoolId = tab_top[tonumber(curpage)];
    this.updateRes();
    this.drawShow(txt_DrawOneCost, oneIcon, 1)
    this.drawShow(txt_DrawTenCost, tenIcon, 2)
    this.tips.text = string.format(getLanguage("Draw_TimeLimit"), logicMgr.HeroManager.getDrawTodayCount(curPoolId), dataTable.getGlobalInt(616));
    -- if curPoolId == "1" then
    --     wishList.visible = true
    -- else
    --     wishList.visible = false
    -- end
    UIRedDots.removeListen("btn_DrawOne");
    UIRedDots.removeListen("btn_DrawTen");

    UIRedDots.addViewListen(PanelResNames.UIDraw, "btn_DrawTen", btn_DrawTen, Config.RedDotsType.Summon, curPoolId, {10});
    UIRedDots.addViewListen(PanelResNames.UIDraw, "btn_DrawOne", btn_DrawOne, Config.RedDotsType.Summon, curPoolId, {1});

    -- 红魔石召唤有倒计时
    if tonumber(curPoolId) == 1 and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FreeSummon, false) then
        this.setDrawOneState(mDiamondSummonState)
    else
        this.setDrawOneState(SUMMON_STATE.Normal)
    end
end

function UIDraw.drawShow(textObj, iconObj, type)
    --type 1 单抽 2 10连
    local needitems = G.dataTable["t_drawpool"][tostring(curPoolId)];
    local costItem;
    local curNum = this.getDrawResNum(resTab[tonumber(curPoolId)]);
    if type == 1 then
        costItem = clone(decodeJsonStrToTabel(needitems.f_1DrawConsume));
    else
        costItem = clone(decodeJsonStrToTabel(needitems.f_10DrawsConsume));
        if btnToggle.selected and curpage == 1 and curNum < 10 then
            local shopInfo = dataTable.getRow("t_shopgoods", globalWish[wishIndex][2])
            costItem[2] =shopInfo["f_Price"][1][2]
        end
    end
    if costItem[2] > curNum then
        local needShopID = dataTable.getRow("t_drawpool", curPoolId);
        local needId = type == 1 and needShopID["f_1DrawShopGoods"] or needShopID["f_10DrawsShopGoods"];
        if btnToggle.selected and curpage == 1 and type==2 then
            needId = globalWish[wishIndex][2]
        end
        if needId ~= 0 then
            local shopInfo = dataTable.getRow("t_shopgoods", needId);
            local moneyInfo = decodeJsonStrToTabel(shopInfo["f_Price"])
            local id = moneyInfo[1][1];
            local num = moneyInfo[1][2];
            local haveNum = logicMgr.ItemManager.getCurrencyCountByModelId(id);
            iconObj.url = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(id)].f_Icon;
            if haveNum >= num then
                textObj.text = "[color=#FFFFFF]" .. num .. "[/color]";
            else
                textObj.text = "[color=#FF0000]" .. num .. "[/color]";
            end
        else
            textObj.text = "[color=#FF0000]" .. costItem[2] .. "[/color]";
            iconObj.url = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(costItem[1])].f_Icon;
        end
    else
        textObj.text = "[color=#FFFFFF]" .. costItem[2] .. "[/color]";
        iconObj.url = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(costItem[1])].f_Icon;
    end
end

-- function UIDraw.DelayEnableDraw()
--     this.isClickDraw = false
-- end

function UIDraw.drawSkills(times)
    if this.last_draw_skill_time and UnityEngineTime.realtimeSinceStartup-this.last_draw_skill_time < (1/Time.timeScale) then
        print("点太快会触发多次")
        return
    end

    times = times or this.lastBuyTime
    buyTime = times;
    local isextra =(btnToggle.selected and curpage==1) and 1 or 0
    if isextra == 1 and buyTime == 1 then
        UISysTips.AddMsg(getLanguage("Draw_WishList_Tips24"))
        closeUI(PanelNames.UIDrawResult)
        return
    end
    this.last_draw_skill_time = UnityEngineTime.realtimeSinceStartup
    if tonumber(showTab[1]) == 6  then
        if not isdirecting then
            UISysTips.AddMsg(getLanguage("Sys_MsgTargetDraw_NoTarget"))
            return
        end    
        if dirnum<=0 then
            if isOpenUI(PanelNames.UIDrawResult) then
                UIDrawResult.onClickContinue();
            end
            return
        end
    end
    if this.curisHerotype then
        if not isoccupation then
            UISysTips.AddMsg(getLanguage("Draw_OccupationDraw_Tips1"))
            return
        end    
    end
    
    -- this.isClickDraw = true;
    -- this.drawCordTime = utimer.delayCall(UIDraw.DelayEnableDraw, 2000)
    this.lastBuyTime = buyTime;
    local surePoolID = curPoolId
    if (curPoolId == "4") then
        surePoolID = UIDrawProbability.curProfessionPage
    end
    if times + logicMgr.HeroManager.getDrawTodayCount(surePoolID) > dataTable.getGlobalInt(616) then
        UISysTips.AddMsg(getLanguage("Draw_TimeLimitReached"));
        if isOpenUI(PanelNames.UIDrawResult) then
            UIDrawResult.onClickContinue()
        end
        return ;
    end
    local needitems = dataTable.getRow("t_drawpool", surePoolID)
    local cost;
    local havnum;
    local needNum = 0
    local needShopID = nil
    if times == 1 then
        cost = decodeJsonStrToTabel(needitems.f_1DrawConsume);
        havnum = logicMgr.ItemManager.getBagNumByTableID(cost[1])
        needNum = cost[2]
        needShopID = needitems["f_1DrawShopGoods"]
    else
        cost = decodeJsonStrToTabel(needitems.f_10DrawsConsume);
        havnum = logicMgr.ItemManager.getBagNumByTableID(cost[1])
        needNum = clone(cost[2])
        if btnToggle.selected and curpage == 1 then
            needShopID = globalWish[wishIndex][2]
            local  shopInfo = dataTable.getRow("t_shopgoods", needShopID)
            needNum = shopInfo.f_Quantity
        else

            needShopID = needitems["f_10DrawsShopGoods"]
        end
    end

    local _cardDic = {}
    _cardDic.draw_pool_id = tostring(this.curPoolId)
    _cardDic.draw_base_id = G.dataTable["t_drawpool"][tostring(this.curPoolId)]["f_LoopGuarantee"]
    local _source = "-1"
    if tostring(this.curpage) == this.tab_top[2] then
        if times == 10 then
            _source = TAManager.GetHeroSource.Friendly_Ten
        elseif times == 1 then
            _source = TAManager.GetHeroSource.Friendly_One
        end 
    else
        if times == 10 then
            _source = TAManager.GetHeroSource.Diamond_Ten
        elseif times == 1 then
            _source = TAManager.GetHeroSource.Diamond_One
        end 
    end
    _cardDic.source = _source
    _cardDic.draw_number = tonumber(times)
    -- _cardDic.cost_item_id = tostring(needShopID)
    -- _cardDic.cost_item_number = needNum
    TAManager.TrackByDictionary("draw_cards_click_draw", _cardDic)

    if havnum < needNum then
        -- 免费单抽
        if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FreeSummon, false) and tonumber(curPoolId) == 1 and times == 1 and drawHandler.diamondFreeCount > 0 then
            this.confirmDraw(times);
            return
        end

        local shopInfo = dataTable.getRow("t_shopgoods", needShopID)
        if (curPoolId == "2") or shopInfo == nil then
            UISysTips.AddMsg(getLanguage("ErrorCode_1208"));
            UIDraw.btnDownState = false;
            buyTime = 0
            if isOpenUI(PanelNames.UIDrawResult) then
                UIDrawResult.onClickContinue()
            end
            return
        end

        local needItemName = HelperFunc.GetItemNameWithoutColor(getLanguage(dataTable.getRow("t_item", shopInfo["f_GoodsID"])["f_ItemName"]))
        local moneyInfo = decodeJsonStrToTabel(shopInfo["f_Price"])
        local needMoneyIDList={};
        local needMoneyNameList={};
        local needMoneyNumList={};
        local content1List={};
        local resUrl = string.format(getLanguage("CommonPop_IconSetting"), shopInfo["f_GoodsID"] or 1)
        local content2 = resUrl..needItemName .. "x" .. needNum--道具名称..数量
        local content1=nil;
        for i = 1, #moneyInfo do
            -- body
            local needMoneyID = moneyInfo[i][1]
            local needMoneyName =HelperFunc.GetItemNameWithoutColor(getLanguage(dataTable.getRow("t_item", moneyInfo[i][1])["f_ItemName"]))
            local needMoneyNum = moneyInfo[i][2]
            local resUrl = string.format(getLanguage("CommonPop_IconSetting"),moneyInfo[i][1] or 1)
            local content1=nil;
            if i~=1 then
                content1 = getLanguage("CommonPop_Tips1a")..resUrl..needMoneyName.."x"..needMoneyNum--道具名称..数量
            else
                content1 = resUrl..needMoneyName.."x"..needMoneyNum--道具名称..数量
            end
            
            table.insert(needMoneyIDList, needMoneyID)
            table.insert(needMoneyNameList, needMoneyName)
            table.insert(needMoneyNumList, needMoneyNum)
            table.insert(content1List, content1)
        end
        content1=table.concat(content1List)
        
        local flags = true
        for i = 1, #moneyInfo do 
            local haveMoneyNum = logicMgr.ItemManager.getBagNumByTableID(needMoneyIDList[i])
            if toNumber(haveMoneyNum) < toNumber(needMoneyNumList[i]) then
                UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),needMoneyNameList[i]))
                UIDraw:SetSource(needMoneyIDList[i])
                AudioManager.Play(2010)
                buyTime = 0
                if isOpenUI(PanelNames.UIDrawResult) then
                    UIDrawResult.onClickContinue()
                end
                flags=false
            end
        end

        if flags then 
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
            pop.Init("1", function(b)
                if b then
                    local thisItem = {}
                    local showData = logicMgr.ShopManager.returnShopData()
                    for i = 1, #showData.shopItems do
                        local item = showData.shopItems[i]
                        if item["shopItemModelId"] == tostring(needShopID) then
                            thisItem = clone(item)
                            break
                        end
                    end
                    thisItem["shopId"] = SHOP_ID
                    thisItem["num"] = (thisItem.shopItemModelId == "101200002" or thisItem.shopItemModelId == "101200003" )and 1 or needNum
                    if btnToggle.selected and curpage == 1 then
                        thisItem["num"] = needNum /10
                    end
                    shopHandler.reqBuyShopItem(thisItem)
                    curDrawInfo = times
                else
                    buyTime = 0
                    if isOpenUI(PanelNames.UIDrawResult) then
                        UIDrawResult.onClickContinue()
                    end
                end
            end, content1, content2) 
        end   
    else
        this.confirmDraw(times);
    end
end

function this.BuySecondTime()
    if (buyTime ~= 0) then
        this.confirmDraw(buyTime);
    end
end

function UIDraw.confirmDraw(times)
    buyTime = 0
    local surePoolID = curPoolId
    if (curPoolId == "4") then
        surePoolID = UIDrawProbability.curProfessionPage
    end
    local poolId = surePoolID;

    if isGuiding and times == 10 then
        isGuiding = false;
        poolId = G.dataTable["t_global"]["302"]["f_int_value"]
    end
    print("请求抽卡", UnityEngineTime.realtimeSinceStartup)
    if (curPoolId == "6") then
        drawHandler.SendAppointDraw(poolId,times)
        return;
    elseif ( this.curisHerotype) then
        drawHandler.SendVocationDraw(times);
        return;
    end
    if btnToggle.selected and curpage==1 then
        if (wishIds[1]== 0 and wishIds[2]== 0) or (wishIds[1]== 0 and hasHeroIds[2] == wishIds[2] ) or (wishIds[2]== 0 and hasHeroIds[1] == wishIds[1] ) then
            UISysTips.AddMsg(getLanguage("Draw_WishList_Tips23"))
            if isOpenUI(PanelNames.UIDrawResult) then
                closeUI(PanelNames.UIDrawResult)
            end
            return
        end
    end
    local isextra =(btnToggle.selected and curpage==1) and 1 or 0
    drawHandler.sendDrawMessage(poolId, times,isextra);
end

function UIDraw.receiveDrawMsgError()
    UIDraw.btnDownState = false;
    if isOpenUI(PanelNames.UIDrawResult) then
        closeUI(PanelNames.UIDrawResult)
    end
end
function UIDraw.receiveDrawMsg(cards)
    print("抽卡结果返回", UnityEngineTime.realtimeSinceStartup)
    -- if this.drawCordTime then
    --     utimer.remove(this.drawCordTime)
    --     this.drawCordTime = nil;
    -- end
    UIDraw.btnDownState = false;
    tab_cards = cards;
    curShowIndex = 0;
    this.updateRes();
    Refreshres()
    if #tab_cards > 1 then
        this.startDrawAnimationAgain();
    else
        this.onContinueShowHero();
    end 
end

function UIDraw.startDrawAnimationAgain()
    if logicMgr.HeroManager.getPlayerDrawIsShip() then
        this.onContinueShowHero();
    else
        local flag = nil;
        for k, v in pairs(tab_cards) do
            local heroconfig = G.dataTable["t_hero"][tostring(v.itemModelId)];
            if heroconfig ~= nil then
                if heroconfig.f_HeroInitialStar >= 60 then
                    flag = true;
                    break;
                end
            end
        end
        showUI(PanelNames.UIDrawAnimation, flag, nil, false, this.onContinueShowHero)
        if isOpenUI(PanelNames.UIDrawResult) then
            UIDrawResult.onCloseUIDrawResult();
        end
    end
end

function UIDraw.onContinueShowHero()
    if isOpenUI(PanelNames.UIDrawResult) then
        UIDrawResult.refreshCard(tab_cards);
    else
        showUI(PanelNames.UIDrawResult, tab_cards);
    end
    DestoryUI(PanelNames.UIDrawAnimation);
    if dirnum<=0 and tonumber(showTab[1])==6 then
        UIDrawResult.Settypecon();
    end
end

function UIDraw.scrollToNext(evt)
    this.showSourceController.selectedIndex = 0;
    if this.spineIsIning then
        return;
    end
    curpage = curpage + 1;
    if curpage > #tab_top then
        curpage = 1;
    end
    this.updataSpineActive();
    if curpage==3 then
        -- body
        this.curisHerotype=true;
    else
        this.curisHerotype=false;
    end

    --aniRightOut:Play(function()
    --    this.initPapers()
    --    aniRightIn:Play();
    --end)
end

function UIDraw.updataSpineActive()
    this.spineOutTime = 1
    this.spineInTime = 0
    this.spineIsIning = true
    this.drawOutTime = utimer.timeCall(function()
        this.spineOutTime = this.spineOutTime - this._spineOutInSpeed
        if this.spineOutTime < 0 then
            this.spineOutTime = 0
        end
        for i = 1, 3 do
            if this.spineSprine[i] then
                this.colorObj.a = this.spineOutTime
                this.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj);
            end
        end
        print("抽卡立绘out .." ..this.spineOutTime);
        if this.spineOutTime <= 0 then
            utimer.remove(this.drawOutTime)
            this.drawOutTime = nil
            this.initPapers()
            this.checkChangeTips()
            this.drawInTime = utimer.timeCall(function()
                this.spineInTime = this.spineInTime + this._spineOutInSpeed
                if this.spineInTime > 1 then
                    this.spineInTime = 1
                end
                for i = 1, 3 do
                    if this.spineSprine[i] then
                        this.colorObj.a = this.spineInTime
                        this.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(this.colorObj)
                    end
                end
                print("抽卡立绘in .." ..this.spineInTime)
                if this.spineInTime >= 1 then
                    this.spineIsIning = nil
                    utimer.remove(this.drawInTime)
                    this.drawInTime = nil
                end
            end, 10, -1)
        end
    end, 10, -1)
end

function UIDraw.scrollToLast(evt)
    this.showSourceController.selectedIndex = 0;
    if this.spineIsIning then
        return;
    end
    curpage = curpage - 1;
    if curpage < 1 then
        curpage = #tab_top;
    end
    this.updataSpineActive();
    --aniLeftOut:Play(function()
    --    this.initPapers()
    --    aniLeftIn:Play();
    --end)
    if curpage==3 then
        -- body
        this.curisHerotype=true;
    else
        this.curisHerotype=false;
    end
end

function UIDraw.receivePoolMsg(msg)
    UIDraw.OpenState = msg.pools
end

function UIDraw.checkChangeTips()   --逻辑很复杂难理解，具体问包子
    if curpage == 1 then
        if logicMgr.HeroManager.GetWishNum() < G.dataTable["t_global"]["406"].f_int_value then  --功能未开启
            txtBaoDi.text = getLanguage("Draw_Hint")
        else
            local insureRemain = logicMgr.HeroManager.GetInsureRemain()    --抽卡次数
            local heroIds = logicMgr.HeroManager.GetWishData()
            local wishLegendHeros = heroIds[7]
            local heroShowList = {} --上阵心愿英雄列表
            for _,v in pairs(wishLegendHeros) do
                if v ~= 0 then
                    table.insert(heroShowList,v)
                end
            end
            local heroShowCount = #heroShowList --上阵心愿英雄个数
            local isAllGet = logicMgr.HeroManager.CheckAllShowHeroGet(heroShowList)   --上阵英雄是否都已实现
            if heroShowCount > 0 then
                if isAllGet then
                    if heroShowCount == 2 then   --上阵英雄满了且都已实现
                        txtBaoDi.text = getLanguage("Draw_Hint")
                    else    --英雄上阵未满但上阵的都已实现
                        txtBaoDi.text = string.format(getLanguage("Draw_WishList_Tips10"),insureRemain,insureRemain)
                    end
                else    --有英雄未实现
                    txtBaoDi.text = string.format(getLanguage("Draw_WishList_Tips14"),insureRemain,insureRemain)
                end
            else
                txtBaoDi.text = string.format(getLanguage("Draw_WishList_Tips10"),insureRemain,insureRemain)
            end
        end
    else
        txtBaoDi.text = "[color=#EBFBFF]10[/color] 次召唤必出 [color=#d789ff]卓越[/color] 或以上品质英雄"
    end
end

--- 单抽状态
--- @param state number 状态值
function UIDraw.setDrawOneState(state)
    if btn_DrawOne == nil then
        return
    end

    --- @type GController
    local stateCtrl = btn_DrawOne:GetController("type")
    if stateCtrl == nil then
        return
    end
    stateCtrl.selectedIndex = state
end

--- 免费时间倒计时展示
function UIDraw.showFreeSummonTime()
    local uiTxtTime = btn_DrawOne:GetChild("time")
    if uiTxtTime == nil then
        return
    end

    local function __checkTimer()
        local leftTime = drawHandler.getNormalSummonFreeLeftTime()
        uiTxtTime.text = string.format(getLanguage("Draw_FreeText2"), HelperFunc.GetTimeStr(leftTime))
        if leftTime <= 0 then
            this.onFreeTimerComplete()
        end
    end

    utimer.remove(mFreeSummonTimerId)
    mFreeSummonTimerId  = utimer.timeCall(__checkTimer, 1000, -1)
    mDiamondSummonState = SUMMON_STATE.Time
    if tonumber(curPoolId) == 1 then
        this.setDrawOneState(mDiamondSummonState)
    end
    __checkTimer()
end

--- 倒计时完成
function UIDraw.onFreeTimerComplete()
    this.removeFreeSummonTimer()
    mDiamondSummonState = SUMMON_STATE.Free
    if tonumber(curPoolId) == 1 then
        this.setDrawOneState(mDiamondSummonState)
    end

    -- 数据更新
    if drawHandler.diamondFreeCount == 0 then
        drawHandler.diamondFreeCount = 1
        FireEvent(Config.EventType.Fresh_Free_Summon)
    end
end

-- 移除计时器
function UIDraw.removeFreeSummonTimer()
    if mFreeSummonTimerId == nil then
        return  
    end
    utimer.remove(mFreeSummonTimerId)
    mFreeSummonTimerId = nil
end

return UIDraw;